package com.mobike.android.os

import pushtest.mobike.com.basic_android.BuildConfig
import java.util.*

/**
 * Created by molikto on 21/11/2017.
 */
class PausableMainThreadQueue {


  private var processing = false
  private val _queue: Queue<Any> = LinkedList()

  fun paused() = !_queue.isEmpty()

  private fun startProcessing() {
    if (processing) throw IllegalArgumentException("Not supported")
    processing = true
  }

  private fun stopProcessing() {
    processing = false
  }

  fun enqueue(action: () -> Unit) {
    startProcessing()
    if (_queue.isEmpty()) {
      action.invoke()
    } else {
      _queue.offer(action)
    }
    stopProcessing()
  }

  fun pause(milliSec: Long) {
    startProcessing()
    _queue.offer(milliSec)
    dequeue()
    stopProcessing()
  }
//
//  fun clearCurrentPause() {
//    val current = currentPause
//    if (current != null) {
//      removeUiThreadCallbacks(current)
//      current.run()
//    }
//  }

  private var currentPause: Runnable? = null

  private fun dequeue() {
    val top = _queue.peek()
    if (top != null) {
      if (top is Long) {
        currentPause = Runnable {
          if (_queue.poll() !is Long) {
            if (BuildConfig.DEBUG) {
              throw IllegalStateException("error state")
            }
          }

          dequeue()
        }
        postOnUiThread(currentPause!!, top)
      } else {
        (_queue.poll() as () -> Unit).invoke()
        dequeue()
      }
    }
  }
}
